import Api from '../api'
import {md5} from '../util'

import Code from './code'

let api, code;
export default class User {
	constructor(options){
		api = new Api(options);
		code = new Code(options)
	}
	fetch(...args){
		return api.genFeatureMod('user')(...args)
	}

	login = async (data) => {
		const param = {
			act: 'login',
			...data,
			user_pass: md5(data.user_pass)
		}

		if(!param.user_id && !param.user_name && !param.user_mail){
			throw new Error("userid, username or usermain must required one!")
		}

		const res = await this.fetch(param)
		return res;
	}
	registry = async data => {
		const param = {
			act: 'reg',
			...data,
			user_pass: md5(data.user_pass)
		}
		const res = await this.fetch(param)
		return res;
	}
	sendActiveMail = async data => {
		const param = {
			act: 'nomail',
			...data
		}
		const res = await this.fetch(param)
		return res;
	}
	view = async usermark => {
		const param = {
			act: 'read'
		}
		if(parseInt(usermark) == usermark){
			param.user_id = usermark
		} else if(~usermark.indexOf('@')){
			param.user_mail = usermark
		} else {
			param.user_name = usermark
		}
		const res = await api.genCommonMod('user', "GET")(param).then(res => {
			if(!!~res.rcode.indexOf('y')){
				return res.code
			} else {
				throw new Error(res.msg);
			}
		}).then(str => code.decode(str))
		return res;
	}
	edit = async data => {
		const param = {
			act: 'edit',
			...data
		}
		if(param.user_pass){
			param.user_pass = md5(param.user_pass);
		}
		const res = await this.fetch(param)
		return res;
	}
	del = async userids => {
		const param = {
			act: 'del',
			user_ids: userids.join('|')
		}
	}
	checkName = async username => {
		const param = {
			act: 'chkname',
			user_name: username
		}
		const res = await api.genCommonMod('user', "GET")(param).then(res => {
            return {
                result: !!~res.rcode.indexOf('y'),
                msg: res.msg
            }
        })
		return res;
	}
	checkEmail = async email => {
		const param = {
			act: 'chkmail',
			user_mail: email
		}
		const res = await api.genCommonMod('user', "GET")(param).then(res => {
            return {
                result: !!~res.rcode.indexOf('y'),
                msg: res.msg
            }
            
        })
		return res;
	}
}